package com.apes.scm.income.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.account.repository.CooperationRepository;
import com.apes.scm.account.ledger.service.LedgerService;
import com.apes.scm.income.model.Income;
import com.apes.scm.income.model.IncomeItem;
import com.apes.scm.income.repository.IncomeItemRepository;
import com.apes.scm.income.repository.IncomeRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.finance.model.IncomeType;
import com.apes.scm.masterdata.finance.repository.IncomeTypeRepository;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 收入服务
 *
 * 注：由于写入的账，以及处理的逻辑都是一样的。此类暂时不使用。2018-12-3
 * @author wuq
 * @create 2018-11-27 10:49
 */
@Service("customerIncomeService")
public class CustomerIncomeService extends DomainService {

    @Autowired
    private IncomeRepository incomeRepository;

    @Autowired
    private IncomeItemRepository incomeItemRepository;

    @Autowired
    LedgerService ledgerService;

    @Autowired
    private PartyRoleRepository partyRoleRepository;



    public Income create(SimpleRequest request){
         Income income = request.getO(Income.class);
         income.setState("sent");
         return incomeRepository.saveAndFlush(income);
     }

     public String delete(SimpleRequest request){
         Income income = request.getO(Income.class);
         incomeRepository.delete(income);
         return "删除成功！";
     }

     public Income update(SimpleRequest request){
         Income income = request.getO(Income.class);
         return incomeRepository.saveAndFlush(income);
     }

     public Income approve(SimpleRequest request){
         Income income = request.getO(Income.class);
         income.setState("approve");
         income.setApproveUID(this.getPerson(request));
         income.setApproveDate(new Date());

         ledgerService.charge(income.getCompany(), income.getDept(), income.getPartner(), income.getCooperation().getInventoryMode(),
                 income.getCooperation().getAccountingMethod(), income.getInnerBusinessKey(), income.getInnerBusinessType(),
                 new Date(), "discount_unsettled", income.getAmount());

         return incomeRepository.saveAndFlush(income);
     }

    /**
     * 平台费用或者平台定损生成费用账单
     * list<list<Map>>
     *     list:数量
     *     list:expenseType 费用类型,source 来源单号,sourceBusinessType 来源单据
     *          origin 源单据,creator 创建人,company 公司,deptId 部门
     *          partner 合作伙伴
     *     Map:reconcileBeginDate 业务开始日期
     *         reconcileEndDate 业务结束时间,amount 金额,note 备注
     *
     * @param request
     * @return
     */
    public void incomeCreate(SimpleRequest request) {
        if("Expense".equals(request.get("sourceBusinessType"))){
            /*平台费用生成费用账单*/
            this.expense(request);
        }else {
            /*平台定损生成费用账单*/
            this.settleIncome(request);
        }
    }

    /**
     * 平台费用生成费用账单
     * @param request
     * @return
     */
    public void expense(SimpleRequest request){
        JSONObject param = request.getJO();
        JSONArray details = param.getJSONArray("details");
        details.forEach(detail ->{
            Set<IncomeItem> incomeItemSet = new HashSet<>();
            Income income = new Income();
            JSONObject temp = (JSONObject) detail;
            temp.getJSONArray("list").forEach(list->{
                IncomeItem incomeItem = new IncomeItem();
                JSONObject tempList = (JSONObject) list;

                //判断此次平台费用单是否生成
                List<Income> incomeList = incomeRepository.findAll(JpaDsl.toCriteriaByEq("source", tempList.getString("source"),
                        "company.id",tempList.getString("company"),"partner.id",tempList.getString("partner"),"inComeCategory.id",param.getString("inComeCategory")));
                if(incomeList.size() > 1)  throw new RuntimeException(tempList.getString("source")+"已生成费用账单，无法再次生成!");

                IncomeType incomeType = SpringManager.getBean(IncomeTypeRepository.class)
                        .findOne(tempList.getString("expenseType"));
                //明细表
                incomeItem.setIncomeType(incomeType);
                incomeItem.setStartDate(tempList.getDate("reconcileBeginDate"));
                incomeItem.setEndDate(tempList.getDate("reconcileEndDate"));
                incomeItem.setRecoveryAmount(0);
                incomeItem.setFreezeAmount(0);
                incomeItem.setIncomeAmount(tempList.getDouble("amount"));
                incomeItem.setDone(false);
                incomeItem.setVersion(0);
                incomeItem.setTax(incomeType.getTax());
                incomeItem.setNote(tempList.getString("note"));
                incomeItem.setAnnex(tempList.getString("annex"));
                incomeItem.setRemark(tempList.getString("id"));
                incomeItemSet.add(incomeItem);

                income.setAmount(income.getAmount()+incomeItem.getIncomeAmount());
                income.setSource(tempList.getString("source"));
                income.setPartner(partyRoleRepository.findOne(tempList.getString("partner")));
                income.setCompany(partyRoleRepository.findOne(tempList.getString("company")));
                income.setDept(SpringManager.getBean(DeptRepository.class).findOne(tempList.getString("deptId")));
                income.setCarLicense(tempList.getString("carLicense"));
            });
            //主表
            income.setIncomeItems(incomeItemSet);
            income.setInComeCategory(SpringManager.getBean(EnumerationRepository.class).findOne(param.getString("inComeCategory")));
            income.setCooperation(SpringManager.getBean(CooperationRepository.class).findOne("distribution"));
            income.setSourceBusinessType(param.getString("sourceBusinessType"));
            income.setCreator(temp.getString("creator"));
            income.setCreateDate(new Date());
            income.setState("sent");
            income.setNote(param.getString("note"));
            request.setData(incomeRepository.saveAndFlush(income));
            this.approve(request);
        });
    }

    /**
     * 平台定损生成费用账单
     * @param request
     * @return
     */
    public void settleIncome(SimpleRequest request){
        JSONObject param = request.getJO();
        Income income = new Income();
        IncomeItem incomeItem = new IncomeItem();
        Set<IncomeItem> incomeItemSet = new HashSet<>();
        IncomeType incomeType = SpringManager.getBean(IncomeTypeRepository.class).findOne(param.getString("expenseType"));

        //判断此次平台定损是否生成
        List<Income> incomeList = incomeRepository.findAll(JpaDsl.toCriteriaByEq("source", param.getString("source")));
        if(incomeList.size() > 0)  throw new RuntimeException(param.getString("source")+"已生成费用账单，无法再次生成!");

        //明细表
        incomeItem.setIncomeType(incomeType);
        incomeItem.setStartDate(param.getDate("reconcileBeginDate"));
        incomeItem.setEndDate(param.getDate("reconcileEndDate"));
        incomeItem.setRecoveryAmount(0);
        incomeItem.setFreezeAmount(0);
        incomeItem.setDone(false);
        incomeItem.setTax(incomeType.getTax());
        incomeItem.setIncomeAmount(param.getDouble("amount"));
        incomeItem.setNote(param.getString("note"));
        incomeItemSet.add(incomeItem);

        //主表
        income.setInComeCategory(SpringManager.getBean(EnumerationRepository.class).findOne("cost"));
        income.setCooperation(SpringManager.getBean(CooperationRepository.class).findOne("distribution"));
        income.setSource(param.getString("source"));
        income.setSourceBusinessType(param.getString("sourceBusinessType"));
        income.setSourceBusinessKey(param.getString("originBusinessType"));
        income.setCreator(param.getString("creator"));
        income.setCreateDate(new Date());
        income.setAmount(param.getDouble("amount"));
        income.setCompany(partyRoleRepository.findOne(param.getString("company")));
        income.setDept(SpringManager.getBean(DeptRepository.class).findOne(param.getString("deptId")));
        income.setPartner(partyRoleRepository.findOne(param.getString("partner")));
        income.setCarLicense(param.getString("carLicense"));
        income.setState("sent");
        income.setNote(param.getString("remark"));
        income.setIncomeItems(incomeItemSet);

        request.setData(incomeRepository.saveAndFlush(income));
        this.approve(request);
    }


}
